package com.cskaoyan.market.db.mybatis;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BooltoByteTypeHandler extends BaseTypeHandler<Boolean> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int index, Boolean aBoolean, JdbcType jdbcType) throws SQLException {
        byte value=toByteValue(aBoolean);
        preparedStatement.setByte(index,value);
    }

    private byte toByteValue(Boolean aBoolean) {
        if (aBoolean == true) {
            return 1;
        } else if (aBoolean == false) {
            return 0;
        }
        return -1;
    }

    @Override
    public Boolean getNullableResult(ResultSet resultSet, String columnLabel) throws SQLException {
        byte anByte = resultSet.getByte(columnLabel);
        Boolean view = toBoolView(anByte);
        return null;
    }

    private Boolean toBoolView(byte anByte) {
        if (anByte == 0) {
            return false;
        } else if (anByte == 1) {
            return true;
        }
        return null;
    }

    @Override
    public Boolean getNullableResult(ResultSet resultSet, int i) throws SQLException {
        byte aByte = resultSet.getByte(i);
        Boolean aBoolean = toBoolView(aByte);
        return aBoolean;
    }

    @Override
    public Boolean getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        byte aByte = callableStatement.getByte(i);
        Boolean aBoolean = toBoolView(aByte);
        return aBoolean;
    }
}
